/**
 * 步骤可视化组件
 */
class StepVisualizer {
    /**
     * 构造函数
     * @param {string|HTMLElement} containerId 容器元素ID或元素本身
     */
    constructor(containerId) {
        // 获取容器元素
        this.container = typeof containerId === 'string' ? 
            document.getElementById(containerId) : containerId;
        
        if (!this.container) {
            throw new Error('找不到容器元素');
        }
    }
    
    /**
     * 绘制单个步骤
     * @param {Object} step 步骤数据
     */
    drawStep(step) {
        // 清空容器
        this.container.innerHTML = '';
        
        // 创建步骤元素
        const stepElement = document.createElement('div');
        stepElement.className = 'step-visualization';
        
        // 添加标题
        const title = document.createElement('h3');
        title.textContent = `步骤 ${step.step_number || ''}`;
        stepElement.appendChild(title);
        
        // 添加详细信息
        const details = document.createElement('div');
        details.className = 'step-details';
        
        // 添加迭代次数
        if (step.iteration !== undefined) {
            const iteration = document.createElement('p');
            iteration.innerHTML = `<strong>迭代次数:</strong> ${step.iteration}`;
            details.appendChild(iteration);
        }
        
        // 添加匹配状态
        if (step.matching_status) {
            const matchingStatus = document.createElement('p');
            matchingStatus.innerHTML = `<strong>匹配状态:</strong> ${step.matching_status.current_matching || '无'}`;
            details.appendChild(matchingStatus);
            
            // 添加稳定性信息
            const stability = document.createElement('p');
            stability.innerHTML = `<strong>稳定性:</strong> ${step.matching_status.stability ? '稳定' : '不稳定'}`;
            details.appendChild(stability);
            
            // 添加阻塞对
            const blockingPairs = document.createElement('p');
            blockingPairs.innerHTML = `<strong>阻塞对:</strong> ${step.matching_status.blocking_pairs || '无'}`;
            details.appendChild(blockingPairs);
        }
        
        // 添加偏好信息
        if (step.shipment_preferences && step.route_preferences) {
            const preferences = document.createElement('div');
            preferences.className = 'step-preferences';
            
            // 货物偏好
            const shipmentPref = document.createElement('div');
            shipmentPref.className = 'shipment-preference';
            shipmentPref.innerHTML = `<h4>货物偏好:</h4><p>${step.shipment_preferences.map(p => 
                `货物 ${p.shipment_id}: ${p.route_preferences.join(', ')}`).join('<br/>')}</p>`;
            preferences.appendChild(shipmentPref);
            
            // 路线偏好
            const routePref = document.createElement('div');
            routePref.className = 'route-preference';
            routePref.innerHTML = `<h4>路线偏好:</h4><p>${step.route_preferences.map(p => 
                `路线 ${p.route_id}: ${p.shipment_preferences.join(', ')}`).join('<br/>')}</p>`;
            preferences.appendChild(routePref);
            
            details.appendChild(preferences);
        }
        
        stepElement.appendChild(details);
        
        // 添加样式类
        stepElement.classList.add('step-visualization');
        
        // 添加到容器
        this.container.appendChild(stepElement);
    }
}
// 匹配过程页面的JavaScript逻辑

// 当前步骤索引和过程数据
let currentStepIndex = 0;
let processSteps = [];
let isPlaying = false;
let playInterval = null;
let stepVisualizer = null;

document.addEventListener('DOMContentLoaded', function() {
    console.log('匹配过程页面已加载');
    
    // 初始化步骤可视化组件
    stepVisualizer = new StepVisualizer('step-container');
    
    // 初始化控制面板
    initControlPanel();
    
    // 加载匹配过程数据
    loadMatchingProcess();
});

// 初始化控制面板
function initControlPanel() {
    // 获取控制按钮
    const prevBtn = document.getElementById('prev-step');
    const playPauseBtn = document.getElementById('play-pause');
    const nextBtn = document.getElementById('next-step');
    const resetBtn = document.getElementById('reset');
    const speedSelect = document.getElementById('speed');
    
    // 添加事件监听器
    prevBtn.addEventListener('click', goToPrevStep);
    playPauseBtn.addEventListener('click', togglePlayPause);
    nextBtn.addEventListener('click', goToNextStep);
    resetBtn.addEventListener('click', resetProcess);
    speedSelect.addEventListener('change', changeSpeed);
}

// 加载匹配过程数据
async function loadMatchingProcess() {
    try {
        showLoading(true);
        
        // 从API获取匹配过程数据
        const process = await apiRequest('/process');
        
        // 更新UI
        updateProcessDisplay(process);
        
        showLoading(false);
    } catch (error) {
        console.error('加载匹配过程失败:', error);
        showError('加载匹配过程失败: ' + error.message);
        showLoading(false);
    }
}

// 更新过程显示
function updateProcessDisplay(process) {
    // 保存过程数据
    if (process.steps) {
        processSteps = process.steps;
    }
    
    // 更新状态信息
    if (process.steps && process.steps.length > 0) {
        const lastStep = process.steps[process.steps.length - 1];
        document.getElementById('iteration-count').textContent = lastStep.iteration || 0;
        document.getElementById('restart-count').textContent = lastStep.restart_count || 0;
        document.getElementById('blocking-pairs').textContent = lastStep.blocking_pairs || 0;
        
        // 显示第一个步骤
        showStep(0);
    } else {
        document.getElementById('step-container').innerHTML = '<p>暂无匹配过程数据</p>';
    }
}

// 显示指定步骤
function showStep(stepIndex) {
    if (stepIndex < 0 || stepIndex >= processSteps.length) {
        return;
    }
    
    currentStepIndex = stepIndex;
    const step = processSteps[stepIndex];
    
    // 更新状态信息
    document.getElementById('iteration-count').textContent = step.iteration || 0;
    document.getElementById('restart-count').textContent = step.restart_count || 0;
    document.getElementById('blocking-pairs').textContent = step.blocking_pairs || 0;
    
    // 使用可视化组件显示步骤
    if (stepVisualizer) {
        stepVisualizer.drawStep(step);
    }
}

// 上一步
function goToPrevStep() {
    if (currentStepIndex > 0) {
        showStep(currentStepIndex - 1);
    }
}

// 播放/暂停
function togglePlayPause() {
    const btn = document.getElementById('play-pause');
    if (!isPlaying) {
        // 开始播放
        btn.textContent = '暂停';
        isPlaying = true;
        const speed = parseFloat(document.getElementById('speed').value);
        const interval = 1000 / speed; // 根据速度调整间隔
        
        playInterval = setInterval(() => {
            if (currentStepIndex < processSteps.length - 1) {
                showStep(currentStepIndex + 1);
            } else {
                // 播放完成
                clearInterval(playInterval);
                isPlaying = false;
                btn.textContent = '播放';
            }
        }, interval);
    } else {
        // 暂停播放
        clearInterval(playInterval);
        isPlaying = false;
        btn.textContent = '播放';
    }
}

// 下一步
function goToNextStep() {
    if (currentStepIndex < processSteps.length - 1) {
        showStep(currentStepIndex + 1);
    }
}

// 重置
function resetProcess() {
    const playPauseBtn = document.getElementById('play-pause');
    if (isPlaying) {
        clearInterval(playInterval);
        isPlaying = false;
    }
    playPauseBtn.textContent = '播放';
    showStep(0);
}

// 改变速度
function changeSpeed() {
    if (isPlaying) {
        // 如果正在播放，重新开始播放以应用新速度
        clearInterval(playInterval);
        const speed = parseFloat(document.getElementById('speed').value);
        const interval = 1000 / speed;
        
        playInterval = setInterval(() => {
            if (currentStepIndex < processSteps.length - 1) {
                showStep(currentStepIndex + 1);
            } else {
                // 播放完成
                clearInterval(playInterval);
                isPlaying = false;
                document.getElementById('play-pause').textContent = '播放';
            }
        }, interval);
    }
}

// 显示加载状态
function showLoading(show) {
    const container = document.getElementById('step-container');
    if (show) {
        container.innerHTML = '<p>正在加载匹配过程数据...</p>';
        console.log('正在加载数据...');
    } else {
        console.log('数据加载完成');
    }
}

// 显示错误信息
function showError(message) {
    const container = document.getElementById('step-container');
    container.innerHTML = `<p style="color: red;">错误: ${message}</p>`;
    console.error(message);
}